<?php
namespace app\system\controller;

use app\common\model\DictModel;
use app\common\model\DictTypeModel;
use think\Request;

class DictController extends BaseController
{

    private $dictModel;
    private $dictTypeModel;

    /**
     * 初始化
     */
    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->dictModel     = new DictModel();
        $this->dictTypeModel = new DictTypeModel();
    }

    /**
     * 字典首页
     * @return mixed
     */
    public function index()
    {
        $typeId   = $this->request->param('type_id', 101);
        $typeList = $this->dictTypeModel->select();
        $dictList = $this->dictModel->where(['type_id' => $typeId])->order('dict_id asc')->select();
        $this->assign('type_id', $typeId);//输出字典分类id
        $this->assign('typeList', $typeList);
        $this->assign('dictList', $dictList);//输出当前分类下的字典列表
        return $this->fetch();
    }

    /**
     * 更新缓存
     */
    public function updateCache()
    {
        $this->dictModel->updateCache();
        $this->success('操作成功！', url('index'));
    }

    /**
     * 添加字典
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            $data   = $this->request->param();
            $result = $this->validate($data, 'DictValidate.add');
            if ($result !== true) {
                $this->error($result);
            }
            if ($this->dictModel->addData($data)) {
                $this->dictModel->updateCache();
                $this->success('添加成功！', url('index', ['type_id' => $data['type_id']]));
            } else {
                $this->error($this->dictModel->getError());
            }
        }
        return $this->fetch();
    }

    /**
     * 修改字典
     */
    public function edit()
    {
        if ($this->request->isAjax()) {
            $data   = $this->request->param();
            $result = $this->validate($data, 'DictValidate.edit');
            if ($result !== true) {
                $this->error($result);
            }
            if ($this->dictModel->editData($data)) {
                $this->dictModel->updateCache();
                $this->success('修改成功', url('index', ['type_id' => $data['type_id']]));
            } else {
                $this->error($this->dictModel->getError());
            }
        }
        $id   = $this->request->param('id');
        $info = $this->dictModel->get($id);
        $this->assign('info', $info);
        return $this->fetch();
    }

    /**
     * 删除字典
     */
    public function del()
    {
        $id = $this->request->param('id');
        if ($this->dictModel->delData($id)) {
            $this->dictModel->updateCache();
            $this->success('删除成功！');
        } else {
            $this->error($this->dictModel->getError());
        }
    }
}
